package com.niodata.dp.app;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.niodata.dp.log.LogUtil;
import com.niodata.dp.util.JsonUtil;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public class AppVariableJsonDeserializer extends JsonDeserializer {

  private static final Logger logger = Logger.getLogger(AppVariableJsonDeserializer.class);

  @Override
  public VariableValue deserialize(JsonParser jp,
      DeserializationContext deserializationContext)
      throws IOException, JsonProcessingException {

    String json = jp.readValueAsTree().toString();
    String type = "";
    JSONObject obj = null;
    try {
      obj = new JSONObject(json);
      type = obj.get("variableType").toString();
    } catch (JSONException e) {
      LogUtil.logStackTrace(logger, e);
    }

    VariableType variableType = VariableType.valueOf(type);

    switch (variableType) {
      case Indicator:
        return JsonUtil.fromJson(IndicatorValue.class, json);
      case Accumulator:
        return JsonUtil.fromJson(AccumulatorValue.class, json);
      case Queue:
        return JsonUtil.fromJson(QueueValue.class, json);
      case CheckPoint:
        return JsonUtil.fromJson(CheckPointValue.class, json);
      default:
        return null;
    }

  }

}
